<?php
include ('BaseController.php');

class CustomerController extends BaseController
{
    protected $tableName = "customer";
    protected $pk = "customer_id";

    public function __construct()
    {
        parent::__construct();
    }

    // GET
    public function reportAmount($id): array {
        $idStr = $this->getIdStr($id);
        $getRes = $this->get($id);

        if (!empty($getRes['data'])) {
            $sql = "CALL report_customer_amount($idStr, @lastName, @firstName);SELECT @lastName;SELECT @firstName;";
            $this->conn->multi_query($sql);
            $result = $this->conn->store_result();
            $rentRecords = $this->getArrayDataFromResult($result);
            mysqli_free_result($result);
            $this->conn->next_result();
            {
                // 跳过空结果
                $this->conn->next_result();
                $this->conn->next_result();
            }
            $result = $this->conn->store_result();
            $lastName = $this->getSingleDataFromResult($result)['@lastName'];
            mysqli_free_result($result);
            $this->conn->next_result();
            $result = $this->conn->store_result();
            $firstName = $this->getSingleDataFromResult($result)['@firstName'];

            $totalCost = 0;
            for ($i = 0; $i < count($rentRecords); $i++) {
                $totalCost += $rentRecords[$i]['cost'];
            }

            $data = [
                "last_name"=> $lastName,
                "first_name" => $firstName,
                "records" => $rentRecords,
                "total_cost" => $totalCost
            ];
            return ReturnHelper::success($data, "数据请求成功");
        }
        else {
            return ReturnHelper::failed([], "查无此人");
        }
    }

    // GET
    public function bestCustomers(): array
    {
        $sql = "CALL best_customers();";
        $result = $this->conn->query($sql);
        $data = $this->getArrayDataFromResult($result);
        return ReturnHelper::success($data, "bestCustomers数据请求成功");
    }
}